import { apiKey } from "./../config/secret";
import { Configuration, OpenAIApi } from "openai";
import CryptoJS from "crypto-js";

const configuration = new Configuration({});

/*
 * 开发环境中key从本地文件读取，开发环境从用户传入或者流水线配置读取
 */
const getApiKey = (key?: string) => {
  let apikeyPool = [];

  // 用户有传可以进来就用用户的key
  if (key) {
    // Decrypt
    const userKeys = CryptoJS.AES.decrypt(
      key,
      "*#&SMARTAI-CHATGPT*$&"
    ).toString(CryptoJS.enc.Utf8);

    apikeyPool.push(userKeys);
  } else {
    const systemKeys = process.env.apiKeys || apiKey;
    apikeyPool = [...apiKey, ...systemKeys];
  }

  // 随机取一个apikey
  const index = Math.floor(Math.random() * apikeyPool.length);
  return apikeyPool[index];
};

const getOpenAi = (key?: string) => {
  const apiKey = getApiKey(key) || "";
  // 重写apikey,保证可以使用传进来的apiKey
  configuration.apiKey = apiKey;
  configuration.baseOptions.headers.Authorization = `Bearer ${apiKey}`;

  // 由于openAi的属性受保护，这里只能通过新建实例的方式
  return new OpenAIApi(configuration);
};

export default getOpenAi;
